package me.firstapp.repository.weixin.weibi.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import me.firstapp.module.weixin.weibi.WeiBiAccount;
import me.firstapp.repository.base.impl.EntityRepositoryImpl;
import me.firstapp.repository.weixin.weibi.WeiBiAccountRepository;

@Repository
public class WeiBiAccountRepositoryImpl extends EntityRepositoryImpl<WeiBiAccount> implements WeiBiAccountRepository {

	@Override
	protected Class<WeiBiAccount> getPersistentClass() {
		return WeiBiAccount.class;
	}

	@Override
	public WeiBiAccount findWeiBiAccountByCardNoAndOpenId(String cardNo, String openId) {
		StringBuilder sql = new StringBuilder(" FROM WeiBiAccount bean WHERE 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		sql.append(" AND bean.cardNo = :cardNo ");
		parameters.put("cardNo", cardNo);

		sql.append(" AND bean.openId = :openId ");
		parameters.put("openId", openId);

		List<WeiBiAccount> result = super.query(WeiBiAccount.class, sql.toString(), parameters);

		return result.isEmpty() ? null : result.get(0);
	}

	@Override
	public List<WeiBiAccount> findWeiBiAccounts(int pageNo, int pageSize) {
		StringBuilder sql = new StringBuilder(" FROM WeiBiAccount bean WHERE 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		List<WeiBiAccount> result = queryForPageList(WeiBiAccount.class, sql.toString(), parameters, pageNo,
				pageSize);
		return result;
	}

	@Override
	public List<WeiBiAccount> findWeiBiAccountsForRank(int limitCount) {
		StringBuilder sql = new StringBuilder(" FROM WeiBiAccount bean WHERE 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		sql.append(" ORDER BY bean.balance DESC ");

		return super.queryForLimit(WeiBiAccount.class, sql.toString(), parameters, limitCount);
	}

	@Override
	public Integer findWeiBiAccountsCounts() {
		StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM WeiBiAccount bean WHERE 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		List<Integer> result = super.query(Integer.class, sql.toString(), parameters);
		return result.isEmpty() ? 0 : result.get(0);
	}

}
